<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: chenju
 * @LastEditTime: 2023-02-02 15:55:27
-->
<template>
  <CDialog
    title="找回密码"
    append-to-body
    destroy-on-close
    :width="640"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
  >
    <div class="edit-op-container main" v-if="dialogVisible">
      <el-form
        ref="formRef"
        style="width: 100%"
        :model="taskForm"
        :rules="obj.rules"
        label-position="top"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="登录账号：" prop="username">
              <el-input v-model.trim="taskForm.username" placeholder="请输入登录邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="验证码：" prop="code">
              <p style="display: flex">
                <el-input
                  v-model="taskForm.code"
                  style="width: 300px; margin-right: 8px"
                  :maxlength="6"
                  placeholder="请输入"
                />
                <el-button class="verify-btn" @click="send1">{{
                  time === 0 ? '发送验证码' : `${time}s 后重试`
                }}</el-button>
              </p>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <CVerifyCodeDialog
      ref="verifyCodeDialogRef"
      :visible="visibleT"
      @confirm="loginConfirm"
      :loading="loading"
    ></CVerifyCodeDialog>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'CResetDialog'
}
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue'
import { CDialog } from '@/components/CDialog'
import CVerifyCodeDialog from '../CVerifyCodeDialog/index.vue'
import { useMessage } from '@/hooks/useMessage'
import * as obj from './rules'
import { pwdRetrieve, sendEmailCode } from '@/apis/user/user'
import { useIntervalFn } from '@vueuse/core'
interface SelectFillTypeDialogProps {
  visible: boolean
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {})
const emit = defineEmits(['update:visible', 'refresh'])
const dialogVisible = computed<boolean>({
  get: () => {
    console.log(props.visible)

    return props.visible
  },
  set: (val) => {
    emit('update:visible', val)
  }
})
watch(
  () => dialogVisible.value,
  (visible) => {
    if (visible) {
      init()
    } else {
      formRef.value?.resetFields()
    }
  }
)

const loading = ref(false)
const { createMessage } = useMessage()
let taskForm = reactive({
  username: '',
  code: ''
})

const formRef = ref()
const verifyCodeDialogRef = ref()
const visibleT = ref<boolean>(false)

// 刷新图像验证码
const refreshCode = () => {
  verifyCodeDialogRef.value?.refreshCode()
}
const loginConfirm = () => {
  send()
}

function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      const params = {
        ...taskForm
      }
      pwdRetrieve(params)
        .then(() => {
          createMessage.success('操作成功')
          dialogVisible.value = false
          init()
          emit('refresh')
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      // createMessage.error('校验失败');
    }
  })
}
function init() {
  loading.value = false
  formRef.value?.resetFields()
  taskForm.username = ''
  taskForm.code = ''
}

const time = ref(0)
const { pause, resume } = useIntervalFn(() => {
  if (time.value <= 0) {
    // 停止递减：停止定时器
    pause()
  } else {
    time.value -= 1
  }
}, 1000)

const send = async () => {
  if (!taskForm.username) {
    createMessage.error('请先输入账号')
    return
  }
  // 没有倒计时才可以发送请求
  if (time.value === 0) {
    const { code, randomStr } = verifyCodeDialogRef.value?.getVerifyCodeInfo()
    const params = {
      username: taskForm.username,
      code,
      randomStr,
      userType: import.meta.env.VUE_APP_CLIENT_TYPE === 'SUPPLIER' ? 'SUPPLIER' : 'GROUP'
    }
    sendEmailCode(params)
      .then(() => {
        createMessage.success('验证码已经发送')
        visibleT.value = false
        time.value = 60
        resume()
      })
      .catch((error: any) => {
        const { response } = error
        // 如果验证码错误，重新刷新验证码，否则关闭弹窗
        if (response?.status === 428) {
          refreshCode()
        } else {
          visibleT.value = false
        }
      })
  } else {
    return
  }
}
const send1 = async () => {
  try {
    await formRef.value?.validateField('username')
  } catch (error) {
    console.log('send valid error', error)
    createMessage.error('请输入正确的账号')
    return
  }
  if (!taskForm.username) {
    createMessage.error('请先输入账号')
    return
  }
  if (time.value === 0) {
    visibleT.value = true
  }
}
</script>
<style lang="scss" scoped>
.g-a-tishicaozuoshuoming {
  margin-right: 6px;
  color: #ffc129;
}
</style>
